package com.situ.mall.upload;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.common.ServerResponse;

@Controller
@RequestMapping("/upload")
public class UploadController {

	@RequestMapping("/uploadImg")
	@ResponseBody
	public ServerResponse uploadImg(MultipartFile file) {
		String fileName = upload(file);

		return ServerResponse.createSuccess("上传成功", fileName);

	}

	public String upload(MultipartFile file) {
		// 为了防止重名，先随机生成一个名字
		String name = UUID.randomUUID().toString().replace("-", "");
		// jsp,png
		String exetension = FilenameUtils.getExtension(file.getOriginalFilename());
		// 对名字进行拼接?
		String fileName = name + "." + exetension;
		// 图片保存地址
		String filePath = "E:\\img\\" + fileName;
		try {
			file.transferTo(new File(filePath));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
}
